package com.test.ssm.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@Controller
public class UploadController {

    @RequestMapping("upload.html")
    @ResponseBody
    public String fileUpload1(@RequestParam("file1") MultipartFile file) {
        try {
            //将上传的文件存在E:/upload/下
            String name = file.getOriginalFilename();
            String extName = name.substring(name.lastIndexOf("."));
            String newName = System.currentTimeMillis() + extName;
            FileUtils.copyInputStreamToFile(file.getInputStream(),
                    new File("D:/upload/", newName
                    ));
            String url = "http://localhost:8080/upload/" + newName;
            //error是0代表成功
            String json = "{\"error\":0,\"url\":\"" + url + "\"}";
            return json;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "{\"error\":1,\"url\":\"\"}";
    }

    @RequestMapping("test.html")
    public String test(String content) {
        System.out.println(content);
        return "index.jsp";
    }
}
